/*
 * author      : 吴中勤 
 * date        : 2018/9/16
 * description : TODO
 */

package com.deepexi.adapter.mq;

import com.deepexi.mq.api.IMessageProcessor;
import com.deepexi.mq.domain.MessageResponse;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EventProcessorImpl implements IMessageProcessor<String> {
    private static final Logger logger = LoggerFactory.getLogger(EventProcessorImpl.class);

    private final String topicName;

    private MessageHandler messageHandler;

    public EventProcessorImpl(String topicName, MessageHandler messageHandler) {
        this.topicName = topicName;
        this.messageHandler = messageHandler;
    }

    @Override
    public MessageResponse process(String message) {

        try {
            // 拆包
            // {
            //      body:{},
            //      "className":"com.deepexi.trade.domain.msg.MsgVO",
            //      "msgId":"d3af83fd15e44339b0531f600935"
            // }
            JSONObject jsonObject = new JSONObject(message);
            String msgBody = jsonObject.getString("body");
            if (null == msgBody)
                throw new JSONException("必须包含 body节点");
            messageHandler.handleMessage(topicName, msgBody);
        } catch (JSONException e) {
            logger.error("消息格式不正确, 必须包含body节点");
            e.printStackTrace();
        } catch (Exception e) {
            logger.error("处理mq出错");
            e.printStackTrace();
        }

        // 如果异常, 再发消息都不能解决, 回应OK
        return MessageResponse.SUCCESS;
    }
}
